package com.demo.security.utils;

import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.demo.security.entity.SysUser;
import com.demo.security.model.Payload;
import com.demo.security.model.SysUserDetails;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * @author: 黑马程序员
 *          生成token以及校验token相关方法
 */
public class JwtUtils {

    private static final String JWT_PAYLOAD_USER_KEY = "user";

    /**
     * 私钥加密token
     *
     * @param userInfo   载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位分钟
     * @return JWT
     */
    public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
        return Jwts.builder().claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo)).setId(createJTI()).setExpiration(new Date(expire * 60 * 1000 + System.currentTimeMillis()))
                .signWith(SignatureAlgorithm.RS256, privateKey).compact();
    }

    /**
     * 私钥加密token
     *
     * @param userInfo   载荷中的数据
     * @param privateKey 私钥
     * @param expire     过期时间，单位秒
     * @return JWT
     */
    public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
        return Jwts.builder().claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo)).setId(createJTI()).setExpiration(new Date(expire * 1000 + System.currentTimeMillis()))
                .signWith(SignatureAlgorithm.RS256, privateKey).compact();
    }

    /**
     * 获取token中的用户信息
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Payload<T> payload = new Payload<>();
        payload.setId(body.getId());
        payload.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
        payload.setExpired(body.getExpiration().getTime());
        return payload;
    }

    /**
     * 获取token中的载荷信息
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Payload<T> payload = new Payload<>();
        payload.setId(body.getId());
        payload.setExpired(body.getExpiration().getTime());
        return payload;
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param publicKey 公钥
     * @return Jws<Claims>
     */
    private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    private static String createJTI() {
        return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
    }

    public static void main(String[] args) throws InvalidKeySpecException, IOException {
        SysUserDetails userDetails = new SysUserDetails(new SysUser(1L, "admin", new BCryptPasswordEncoder().encode("123456"), true));
        String publicKey = "/cert/RSA_1637893836223.pub";
        String privateKey = "/cert/RSA_1637893836223.key";
        String token = generateTokenExpireInSeconds(userDetails, RSAUtils.getPrivateKey(privateKey), 86400);
        System.out.println(token);
        Payload<SysUserDetails> payload = getInfoFromToken(token, RSAUtils.getPublicKey(publicKey), SysUserDetails.class);
        System.out.println(JsonUtils.toString(payload));
    }
}